package com.perceptivesoftware.licensing.client.dto;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.rpc.IsSerializable;
import com.perceptivesoftware.licensing.client.common.util.NPAction;
import com.perceptivesoftware.licensing.client.common.util.NPType;
import com.perceptivesoftware.licensing.client.common.util.PerceptivePermission;

public class PermissionsDTO implements IsSerializable {
	ArrayList<PerceptivePermission> permissions = new ArrayList<PerceptivePermission>();

	public PermissionsDTO() {/* For serialization */
	}

	public void addPermission(final PerceptivePermission perceptivePermission) {
		permissions.add(perceptivePermission);
	}

	public List<PerceptivePermission> getPermissions() {
		return permissions;
	}

	public void setPermissions(final ArrayList<PerceptivePermission> permissions) {
		this.permissions = permissions;
	}

	public PerceptivePermission getPermission(final NPType nptype,
			final NPAction npaction, final String inItemCode) {
		String itemCode = inItemCode;
		if (itemCode != null && itemCode.equals("0")) {
			itemCode = null;
		}
		for (final PerceptivePermission np : permissions) {
			// if one is null and the other is not, not a match
			String npItemCode = np.getItemCode();
			if (npItemCode != null && npItemCode.equals("0")) {
				npItemCode = null;
			}
			if ((itemCode == null && npItemCode != null)
					|| (itemCode != null && npItemCode == null)) {
				continue;
			}
			// if both are null it is a match, if neither are, do .equals on the
			// Long
			if (itemCode != null && npItemCode != null) {
				if (!itemCode.equals(npItemCode)) {
					continue;
				}
			}
			if (!nptype.equals(np.getType())) {
				continue;
			}
			if (!npaction.equals(np.getAction())) {
				continue;
			}
			return np;
		}
		final PerceptivePermission np = new PerceptivePermission(nptype, npaction,
				itemCode, false);
		permissions.add(np);
		return np;
	}

	public List<PerceptivePermission> getDirtyPermissions() {
		final ArrayList<PerceptivePermission> al = new ArrayList<PerceptivePermission>();
		for (final PerceptivePermission np : permissions) {
			if (np.isDirty()) {
				al.add(np);
			}
		}
		return al;
	}

	public void addPermissions(final List<PerceptivePermission> permissions) {
		for (final PerceptivePermission np : permissions) {
			addPermission(np);
		}
	}

	public List<PerceptivePermission> getCascadePermissions() {
		final ArrayList<PerceptivePermission> al = new ArrayList<PerceptivePermission>();
		for (final PerceptivePermission np : permissions) {
			if (np.getHasChangedForCascade()) {
				al.add(np);
			}
		}
		return al;
	}
}
